package com.baosight.sczx.zm.cn.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cn.CalculateStock;
import com.baosight.sczx.common.zm.cInterface.cn.CustomInfo;
import com.baosight.sczx.zm.cn.domain.ZMCNCoalAccount;
/**
 * 洗煤质量台帐
 */
public class ServiceZMCN55 extends ServiceEPBase {
	/**
	 * <p>Function: initLoad</p>
	 * <p>Description: 初始化</p> 
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		inInfo.addBlock(EiConstant.resultBlock).set(EiConstant.limitStr, "50");//设置每页默认显示记录数
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}
	/**
	 * <p>Function: query</p>
	 * <p>Description: 查询</p> 
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		String fdYear=inInfo.getString("fdYear");
		String fdMonth=inInfo.getString("fdMonth");
		String fdDepartmentId=inInfo.getString("fdDepartmentId");
		if(fdYear!=null && !fdYear.trim().equals("")){
			inInfo.setCell("inqu_status", 0, "fdYear", fdYear);
		}
		if(fdMonth!=null && !fdMonth.trim().equals("")){
			inInfo.setCell("inqu_status", 0, "fdMonth", fdMonth);
		}
		if(fdDepartmentId==null || fdDepartmentId.trim().equals("")){
			fdDepartmentId=(String)((HashMap<?, ?>)inInfo.getBlock("inqu_status").getRows().get(0)).get("fdDepartmentId");
		}
		if(fdDepartmentId!=null && !fdDepartmentId.trim().equals("")){
			if(UserSession.getInSessionProperty("orgCode").equals(fdDepartmentId)){
				//查看部门和登录部门相同，则查询当前部门数据
				inInfo.setCell("inqu_status", 0, "query",  "yes");
				inInfo.setCell("inqu_status", 0, "fdDepartmentId",  fdDepartmentId);
			}else{
				//查询部门和登录部门不同，则要分开判断登录人是不是中心站或者管理人员
				//中心站和管理人员是可以查看所有数据的
				inInfo.setCell("inqu_status", 0, "query_report",  "yes");
				if(UserSession.getInSessionProperty("orgCode").equals("D.1022301")
					||UserSession.getInSessionProperty("orgCode").equals("D.1022302")){
					inInfo.setCell("inqu_status", 0, "fdDepartmentId",  fdDepartmentId);
				}else{
					//普通人员查看部门数据，只能看自己部门
					inInfo.setCell("inqu_status", 0, "fdDepartmentId",  "not permission query");
				}
			}
		}else{
			inInfo.setCell("inqu_status", 0, "other",  "yes");
			inInfo.setCell("inqu_status", 0, "fdDepartmentId",  UserSession.getInSessionProperty("orgCode"));
		}
		inInfo.setCell("inqu_status", 0, "code_type", "洗煤煤样");//用来区分按照样品类型过滤
		EiInfo outInfo = super.query(inInfo, "ZMCNCoalAccount.query", new ZMCNCoalAccount());
		outInfo.addBlock(StaticBlocks.getBlockData("cmes.cn.minestockplace", new String[] { " ", "猫儿沱" }, new String[] {  " ", "猫儿沱"  }, false));// 地点
		outInfo.addBlock(CustomInfo.getInstance().getCustomBlock("cmes.cn.custom", "fdShortName", "fdKeyId", "","销售"));
		outInfo.set("fdDepartment", UserSession.getInSessionProperty("orgName"));//单位的默认值		
//		outInfo.addBlock(StaticBlocks.getBlockData("cmes.ch.status", new String[] { "草拟", "上报", "已发布" }, new String[] { "草拟", "上报", "已发布" }, false));// 状态
//		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cp.department", "orgCode", "orgName", false));
//		outInfo.set("fdCreatorId", UserSession.getUserId());//登录人的默认值
//		outInfo.set("fdCreator", UserSession.getInSessionProperty("UserCname"));
//		outInfo.set("fdCreateDepartmentId", UserSession.getInSessionProperty("orgCode"));//单位的默认值		
//		outInfo.set("fdCreateDepartment", UserSession.getInSessionProperty("orgName"));//单位的默认值
		return outInfo;
	}	
	
	/**
	 * <p>Function: insert</p>
	 * <p>Description: 新增</p> 
	 */
	@Override	
	public EiInfo insert(EiInfo inInfo) {
		EiInfo outInfo = new EiInfo();
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			ServiceZMCN00 sz00=new ServiceZMCN00();
			_dom.setFdCurrentDate(sz00.getDateFromMineCode(_dom.getFdMyNum()));
			_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CN_COAL_ACCOUNT"));
			_dom.setFdDepartment(UserSession.getInSessionProperty("orgName").toString());
			_dom.setFdDepartmentId(UserSession.getInSessionProperty("orgCode").toString());
			if(_dom.getFdPlaceId()==null||_dom.getFdPlaceId().trim().equals("")){
				_dom.setFdPlaceId(UserSession.getInSessionProperty("orgName").toString());
			}
			this.dao.insert("ZMCNCoalAccount.insert", _dom);
		}
		//计算调量结余累计
		try{
			CalculateStock cs=new CalculateStock();
			cs.calculateSumStockModify(eiBlock, "洗煤煤样");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：洗煤煤样台帐计算调量结余累计失败servicezmcn55");
			return outInfo;
		}
		outInfo = this.query(inInfo);
		outInfo.setStatus(1);
		outInfo.setMsg("操作" + rowcount + "记录成功");
		return outInfo;
	}
	 
	/**
	 * <p>Function: update</p>
	 * <p>Description: 修改</p> 
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		EiInfo outInfo = new EiInfo();
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			ServiceZMCN00 sz00=new ServiceZMCN00();
			_dom.setFdCurrentDate(sz00.getDateFromMineCode(_dom.getFdMyNum()));
			if(_dom.getFdPlaceId()==null||_dom.getFdPlaceId().trim().equals("")){
				_dom.setFdPlaceId(UserSession.getInSessionProperty("orgName").toString());
			}
			this.dao.update("ZMCNCoalAccount.update", _dom);
		}
		//计算调量结余累计
		try{
			CalculateStock cs=new CalculateStock();
			cs.calculateSumStockModify(eiBlock, "洗煤煤样");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：洗煤煤样台帐计算调量结余累计失败servicezmcn55");
			return outInfo;
		}
		outInfo = this.query(inInfo);
		outInfo.setStatus(1);
		outInfo.setMsg("操作" + rowcount + "记录成功");
		return outInfo;
	}	
	/**
	 * <p>Function: delete</p>
	 * <p>Description: 删除</p> 
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		EiInfo outInfo = new EiInfo();
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			this.dao.delete("ZMCNCoalAccount.delete", _dom);
		}
		//计算调量结余累计
		try{
			CalculateStock cs=new CalculateStock();
			cs.calculateSumStockModify(eiBlock, "洗煤煤样");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：洗煤煤样台帐计算调量结余累计失败servicezmcn55");
			return outInfo;
		}
		outInfo = this.query(inInfo);
		outInfo.setStatus(1);
		outInfo.setMsg("操作" + rowcount + "记录成功");
		return outInfo;
	}	 
	
	/**
	 * 上报
	 * <p>Function: report</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午04:07:27 张志芳
	 * </p>
	 *
	 */
	public EiInfo report(EiInfo inInfo)
	{
		String retMsg="";
		//生效的时候置汇报时间为当前时间
		String reportdate=StaticTools.getDate();
		EiInfo outInfo=new EiInfo(); 
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			eiBlock.setCell(i, "fdReportTime", reportdate);
			eiBlock.setCell(i, "fdStatus", "上报");
		}
		//计算调量结余累计
		try{
			CalculateStock cs=new CalculateStock();
			cs.calculateSumStockModify(eiBlock, "洗煤煤样");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：洗煤煤样计算调量结余累计失败servicezmcn55");
			return outInfo;
		}	
		//计算库存
		try{
			CalculateStock cs=new CalculateStock();
			retMsg=cs.calculateStockMET(eiBlock,"洗煤","上报");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：洗煤台帐计算库存失败servicezmcn55");
			return outInfo;
		}
		if(retMsg.equals("ok")){
			super.update(inInfo, "ZMCNCoalAccount.report");
			outInfo = this.query(inInfo);
			outInfo.setStatus(1);
			outInfo.setMsg("操作" + rowcount + "记录成功");
		}else{
			outInfo.setStatus(-1);
			outInfo.setMsg(retMsg);
		}
		return outInfo;   
	
	}
	
	/**
	 * 退回
	 * <p>Function: revert</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午04:07:27 张志芳
	 *    2016-12-23 11:34:58 李红星 modify
	 * </p>
	 *
	 */
	public EiInfo revert(EiInfo inInfo)
	{
		String retMsg="";
		//退回的时候置空汇报时间
		String reportdate="";
		EiInfo outInfo=new EiInfo(); 
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		for (int i = rowcount-1; i >=0 ; i--) {
			eiBlock.setCell(i, "fdReportTime", reportdate);
			eiBlock.setCell(i, "fdStatus", "草拟");
		}
		//退回后不需要计算调量结余累计
		//计算库存
		try{
			CalculateStock cs=new CalculateStock();
			retMsg=cs.calculateStockMET(eiBlock,"洗煤","退回");
		}catch(Exception e){
			e.printStackTrace();
			outInfo.setStatus(-1);
			outInfo.setMsg("操作" + rowcount + "记录失败：毛煤台帐计算库存失败servicezmcn51");
			return outInfo;
		}
		if(retMsg.equals("ok")){
			super.update(inInfo, "ZMCNCoalAccount.report");
			outInfo = this.query(inInfo);
			outInfo.setStatus(1);
			outInfo.setMsg("操作" + rowcount + "记录成功");
		}else{
			outInfo.setStatus(-1);
			outInfo.setMsg(retMsg);
		}
		return outInfo;   
	
	}
	
	/**
	 * 校验是否可以操作
	 * <p>Function: validate2</p>
	 * <p>Description: 检验范围：退回必须从日期最大的记录开始。</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2016-12-23 10:30:14 李红星
	 * </p>
	 *
	 */
	public EiInfo validate2(EiInfo inInfo ) {
		// TODO Auto-generated method stub
		EiBlock eiBlock = inInfo.getBlock("result");
		int minDateIndex = eiBlock.getRowCount()-1;
		String fdCurrentDate=eiBlock.getCell(minDateIndex, "fdCurrentDate").toString();
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdCurrentDate", fdCurrentDate);
		params.put("fdDepartmentId", UserSession.getInSessionProperty("orgCode").toString());
		params.put("code_type", "洗煤煤样");
		List<?> result = dao.query("ZMCNCoalAccount.validate2", params);
		if(result!=null && result.size()>0){
			inInfo.setStatus(-1);
			inInfo.setMsg("操作记录失败：所勾选的记录不是日期最晚的记录。提示：为了保证库存量计算正确，请先从日期最大的“生效”记录开始退回");
			inInfo = this.query(inInfo);
			return inInfo;
		}
		inInfo.setStatus(1);
		return inInfo;
	}
	
	/**
	 * 校验是否可以操作
	 * <p>Function: validate1</p>
	 * <p>Description: 检验范围：上报必须从日期最小的记录开始。如果本次批量操作没有勾选日期最小的草拟记录，则禁止操作</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2016-10-20 22:31:51 李红星
	 * </p>
	 *
	 */
	public EiInfo validate1(EiInfo inInfo ) {
		// TODO Auto-generated method stub
		EiBlock eiBlock = inInfo.getBlock("result");
		int minDateIndex = eiBlock.getRowCount()-1;
		String fdCurrentDate=eiBlock.getCell(minDateIndex, "fdCurrentDate").toString();
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdCurrentDate", fdCurrentDate);
		params.put("fdDepartmentId", UserSession.getInSessionProperty("orgCode").toString());
		params.put("code_type", "洗煤煤样");
		List<?> result = dao.query("ZMCNCoalAccount.validate1", params);
		if(result!=null && result.size()>0){
			inInfo.setStatus(-1);
			inInfo.setMsg("操作记录失败：所勾选的记录不是日期最早的记录。提示：为了保证库存以及调整量累计值计算正确，请先从日期最小的“草拟”记录开始上报");
			inInfo = this.query(inInfo);
			return inInfo;
		}
		inInfo.setStatus(1);
		return inInfo;
	}
	
	/**
	 * 校验是否可以操作
	 * <p>Function: validate</p>
	 * <p>Description: 检验范围：1、不能新增历史数据：判断依据，如果数据库里边存在比当前记录日期大的记录，则返回失败
	 *                        2、修改历史数据时不能修改日期和数量字段</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2016-10-20 22:45:48 李红星
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	public EiInfo validate(EiInfo inInfo) {
		ZMCNCoalAccount _dom = new ZMCNCoalAccount();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		String oper=(String)inInfo.get("efCurButtonEname");
		for (int i = 0;i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String> params = new HashMap<String, String>();
			String fdStatus=_dom.getFdStatus();
			String fdCurrentDate = _dom.getFdCurrentDate();
			String code_type = "洗煤煤样";
			float fdCl=_dom.getFdCl().floatValue();
			float fdCltz=_dom.getFdCltz().floatValue();
			float fdCheNum=_dom.getFdCheNum().floatValue();
//			if(oper.equalsIgnoreCase("update"))
//			{
				if(fdStatus.equals("草拟")){
					params.put("fdCurrentDate", fdCurrentDate);
					params.put("fdDepartmentId", UserSession.getInSessionProperty("orgCode").toString());
					params.put("code_type", code_type);
				}else{
					params.put("fdKeyId", _dom.getFdKeyId());
				}
//			}else{
//				params.put("fdCurrentDate", fdCurrentDate);
//				params.put("fdDepartmentId", UserSession.getInSessionProperty("orgCode").toString());
//				params.put("code_type", code_type);
//			}
			List result = dao.query("ZMCNCoalAccount.validate", params);
			boolean iftrue=true;
			if(result != null && result.size() > 0) {
				StringBuffer msg = new StringBuffer("系统检测到");
				if(fdStatus.equals("草拟")){
/*					iftrue=false;
					if(!oper.equalsIgnoreCase("update")){
						msg.append(" 还有更新日期的记录已经上报。不能增加历史记录，请检查！");
					}else{
						msg.append(" 还有更新日期的记录已经上报。不能将当期日期修改为历史记录，请检查！");
					}*/
				}else{
					ZMCNCoalAccount _temp = (ZMCNCoalAccount)result.get(0);
					if(_temp.getFdCurrentDate()!=null && !_temp.getFdCurrentDate().equals(fdCurrentDate)){
						iftrue=false;
						msg.append(" “日期” ");
					}
					if(_temp.getFdCl() != null && _temp.getFdCl().floatValue()!=fdCl) {
						iftrue=false;
						msg.append(" “销量” ");
					}
					if(_temp.getFdCltz()!= null && _temp.getFdCltz().floatValue()!=fdCltz) {
						iftrue=false;
						msg.append(" “销量调整” ");
					}
					if(_temp.getFdCheNum() != null && _temp.getFdCheNum().floatValue()!=fdCheNum) {
						iftrue=false;
						msg.append(" “车数” ");
					}
					msg.append("修改了。不能修改已经上报记录的日期或数量值，请检查！提示：已经上报的记录只能修改化验数据");
				}
				if(!iftrue){
					inInfo.setStatus(-1);
					inInfo.setMsg(msg.toString());
				}
				return inInfo;
			}
			//以下增加重复性校验。主要是根据 编码不能重复。add by lhx at 2017-3-30 20:49:06
			String fdKeyId=_dom.getFdKeyId();
			String fdMyNum=_dom.getFdMyNum();
			CalculateStock cs=new CalculateStock();
			if(cs.validateMineCode(fdKeyId, fdMyNum)){
				inInfo.setStatus(-1);
				inInfo.setMsg("煤样编码“"+fdMyNum+"”已经存在了，不能重复增加相同编码的化验记录。请检查!");
				return inInfo;
			}
		}
		inInfo.setStatus(1);
		return inInfo;
	}

}